/**
 * <pre>
   Copyright 2016 aaron.sd

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 * </pre>
 * 
 * @author aaronwong.sd@foxmail.com
 * @version 下午8:55:02
 */
package com.iwechat.service.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iwechat.mybatis.generator.dao.TemplateMessageMapper;
import com.iwechat.mybatis.generator.model.TemplateMessage;
import com.iwechat.service.MutexDbScan;
import com.iwechat.service.TempMsgPriorityQueue;
import com.iwechat.util.PropertyUtils;

/**
 * 互斥消息扫描实现
 * 
 * @author aaronwong.sd@foxmail.com
 */
@Service
public class MutexDbScanImpl implements MutexDbScan {
    private static final Logger   logger = LogManager.getLogger();

    @Autowired
    private TemplateMessageMapper mesgMapper;

    @Resource(name = "RedisPriorityQuenue")
    TempMsgPriorityQueue        queue;

    private int                   pageSize;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = false)
    public List<TemplateMessage> scanDb() {
        // 通过对事务中的一个update操作对事务加互斥锁
        mesgMapper.lock();
        // 取二者的较小值
        int quefree = this.queue.getFreeSize();
        if (pageSize < quefree) {
            quefree = pageSize;
        }
        // 扫描消息-分页
        PageHelper.startPage(1, quefree);
        List<TemplateMessage> messages = mesgMapper.query4Send();
        PageInfo<TemplateMessage> page = new PageInfo<TemplateMessage>(messages);
        List<TemplateMessage> pageList = page.getList();

        if (pageList != null && pageList.size() > 0) {
            List<Long> list = new ArrayList<Long>(pageList.size());
            for (TemplateMessage mesg : pageList) {
                list.add(mesg.getSeqnb());
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", TemplateMessage.Status.STATUS_1_PROCESS);
            map.put("list", list);
            mesgMapper.updateStausBatch(map);

        }
        return pageList;
        // 非扫描消息
        // List<TemplateMessage> messages = mesgMapper.query4Send();
        //
        // if (messages != null && messages.size() > 0) {
        // List<Long> list = new ArrayList<Long>(messages.size());
        // for (TemplateMessage mesg : messages) {
        // list.add(mesg.getSeqnb());
        // }
        // Map<String, Object> map = new HashMap<String, Object>();
        // map.put("status", TemplateMessage.Status.STATUS_1_PROCESS);
        // map.put("list", list);
        // mesgMapper.updateStausBatch(map);
        //
        // }
        // return messages;

    }

    @PostConstruct
    public void init() {
        pageSize = PropertyUtils.getInstance().getIntValue("settings", "template.message.scan.pageSize");
        logger.info("### " + this + " init succeed!");
    }

}
